<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon> </el-alert>选择商品分类:
      <el-cascader v-model="selectKey" :options="cateList" :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name' }" @change="selectCate"></el-cascader>

      <el-tabs v-model="activeName" @tab-click="tabClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="dialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="params" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable :disable-transitions="false" @close="removeTag(i, scope.row)">
                  {{ tag }}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="500"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openEditDialog(scope.row)" icon="el-icon-edit">修改</el-button>
                <el-button size="mini" type="danger" @click="openDeleteDialog(scope.row)" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!--  静态属性-->
        <el-tab-pane label="静态属性" name="only">
          <el-button :disabled="isBtnDisabled" type="primary" size="mini" @click="dialogVisible = true">添加属性</el-button>
          <!--  静态属性表格-->
          <el-table :data="params" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag :key="i" v-for="(tag, i) in scope.row.attr_vals" closable :disable-transitions="false" @close="removeTag(i, scope.row)">
                  {{ tag }}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"> </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="500"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openEditDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" @click="openDeleteDialog(scope.row)" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加属性对话框 -->
    <el-dialog :title="titleText" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="labelText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogClosed">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog :title="titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="labelText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data() {
    return {
      cateList: [],
      selectKey: [],
      params: [],
      activeName: 'many',
      // but: true
      dialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [{ required: true, message: '请输入参数名称', trigger: 'blur' }]
      },
      attr_id: 0
    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    isBtnDisabled() {
      return this.selectKey.length == 3 ? false : true
    },
    cateId() {
      return this.selectKey.length == 3 ? this.selectKey[2] : null
    },
    titleText() {
      return this.activeName == 'many' ? '添加动态参数' : '添加静态属性'
    },
    labelText() {
      return this.activeName == 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    async getcateParams() {
      if (this.selectKey.length !== 3) {
        this.params = []
        this.selectKey = []
        return
      }
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      this.params = res.data

      console.log(this.params)
    },
    selectCate() {
      console.log(this.selectKey)
      // if (this.selectKey.length === 3) {
      //   this.but = false
      //   this.getcateParams()
      // } else {
      //   this.but = true
      //   this.activeParams = []
      //   this.staticParams = []
      //   this.selectKey = []
      //   return
      // }
      this.getcateParams()
    },
    tabClick() {
      this.getcateParams()
    },
    // 添加参数对话框相关
    addDialogClosed() {
      this.dialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    addParams() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('添加失败')
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)

        this.$message.success('添加成功')
        // this.addDialogClosed()
        this.dialogVisible = false
        this.getcateParams()
      })
    },
    // 修改参数对话框相关
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getcateParams()
      })
    },
    openEditDialog(row) {
      this.editDialogVisible = true
      this.editForm.attr_name = row.attr_name
      this.attr_id = row.attr_id
    },
    async openDeleteDialog(row) {
      const res = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      if (res == 'confirm') {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getcateParams()
        this.$message.success('删除成功!')
      }
    },
    removeTag(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveVal(row)
    },
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获得焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    async handleInputConfirm(row) {
      if (row.inputValue.trim()) {
        console.log(row.inputValue.trim())
        row.attr_vals.push(row.inputValue.trim())
        console.log(row.attr_vals)
        this.saveVal(row)
      }
      row.inputVisible = false
      row.inputValue = ''
    },

    async saveVal(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    }
  }
}
</script>

<style lang="less" scoped>
.el-cascader {
  margin: 15px 0 15px 0;
}
.el-table {
  font-size: 10px;
}
.el-tag {
  margin-left: 15px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
